package com.sw.zk.zk;

import com.alibaba.druid.pool.DruidDataSource;
import com.sw.zk.db.ApplicationContextUtil;
import com.sw.zk.db.Constants;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * zk 服务器
 */
@Configuration
public class ZKServerConfig {
    public static ZkClient zkClient;

    /**
     * 初始化zk客户端
     * @return
     */
    @Bean
    public ZkClient client(){
        ZkClient zkClient=new ZkClient("localhost:2181");
        if(!zkClient.exists(Constants.DBPATH)){
            zkClient.createPersistent(Constants.DBPATH);
        }
        return zkClient;
    }

    static {
        zkClient = new ZkClient("127.0.0.1:2181");
        if (!zkClient.exists(Constants.DBPATH)){
            zkClient.createPersistent(Constants.DBPATH);
        }
        watchDataBaseConfigChange();
    }
    public static void watchDataBaseConfigChange() {
        zkClient.subscribeDataChanges(Constants.DBPATH, new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object object) throws Exception {
                DbZkData dataBaseConfig = (DbZkData) object;
                System.out.println("数据源变更" + dataBaseConfig);
                DruidDataSource dataSource = (DruidDataSource) ApplicationContextUtil.getBean(DruidDataSource.class);
                if (dataSource.isInited()) {
                    // 先关闭，再重启
                    dataSource.close();
                    dataSource.restart();
                }
                // 设置新的数据库
                dataSource.setUrl(dataBaseConfig.getUrl());
                dataSource.setUsername(dataBaseConfig.getUsername());
                dataSource.setPassword(dataBaseConfig.getPassword());
                dataSource.setDriverClassName(dataBaseConfig.getDriver());
                // 初始化数据源
                dataSource.init();
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {

            }
        });
    }
    /**
     * 读取数据库配置文件
     * @return
     */
    public DbZkData getDbZkData(){
        DbZkData dbZkData = zkClient.readData(Constants.DBPATH);
        return dbZkData;
    }

    /**
     *
     * @param zkClient
     * @param dbUrl
     */
    public static void setDataBaseConfig(ZkClient zkClient,String dbUrl) {
        DbZkData dbZkData = new DbZkData();
        dbZkData.setDriver("com.mysql.jdbc.Driver");
        dbZkData.setUrl(dbUrl);
        dbZkData.setUsername("root");
        dbZkData.setPassword("admin");

        if (!zkClient.exists(Constants.DBPATH)) {
            zkClient.createPersistent(Constants.DBPATH);
        } else {
            zkClient.writeData(Constants.DBPATH, dbZkData);
        }
    }
}
